package juc.lock;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author fangbin
 * @desc 演示公平和非公平锁,打印案例
 * @date 2020/6/8 13:04
 */
public class FairLock {

    public static void main(String[] args) {
        PrintQueue printQueue = new PrintQueue();
        Thread[] threads = new Thread[10];
        for(int i=0;i<10;i++){
          threads[i] = new Thread(new Job(printQueue));
        }
        for(int i=0;i<10;i++){
           threads[i].start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class PrintQueue{
    private Lock queueLock = new ReentrantLock(true);
    public void printJob(Object document){
        queueLock.lock();
        try{
            int duration = new Random().nextInt(10)+1;
            System.out.println(Thread.currentThread().getName()+"第一次打印，需要"+duration+"秒");
            Thread.sleep(duration*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            queueLock.unlock();
        }

        queueLock.lock();
        try{
            int duration = new Random().nextInt(10)+1;
            System.out.println(Thread.currentThread().getName()+"第二次打印，需要"+duration+"秒");
            Thread.sleep(duration*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            queueLock.unlock();
        }
    }
}

class Job implements Runnable{
    PrintQueue printQueue;

    public Job(PrintQueue printQueue) {
        this.printQueue = printQueue;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始打印");
        printQueue.printJob(new Object());
        System.out.println(Thread.currentThread().getName()+"打印完毕");
    }


}